package cn.chengpengper.im.platform.common.risk.rule.service.impl;

import cn.chengpengper.im.platform.common.exception.ImException;
import cn.chengpengper.im.platform.common.model.constants.ImPlatformContants;
import cn.chengpengper.im.platform.common.model.enums.HttpCode;
import cn.chengpengper.im.platform.common.risk.enums.RuleEnum;
import cn.chengpengper.im.platform.common.risk.rule.service.RuleChainService;
import cn.chengpengper.im.platform.common.risk.rule.service.base.BaseRuleChainService;
import cn.chengpengper.im.platform.common.session.UserSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/*@formatter:off*/

/**
 * ____________________
 * < 神兽护体，永无bug! >
 * --------------------
 *
 * @author catwing
 * @version v1.0.0
 * @date 2024/12/8 15:26
 * @description 账户安全校验规则
 */

/*@formatter:on*/

@Slf4j
@Component
public class AuthRuleChainService extends BaseRuleChainService implements RuleChainService {

    @Value("${diy.im.rule.authRule.order:10}")
    private Integer authRuleOrder;

    @Override
    public HttpCode execute(HttpServletRequest request, Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            return HttpCode.SUCCESS;
        }
        UserSession userSession = this.getUserSession(request);
        if (Objects.isNull(userSession)) {
            log.error("AuthRuleChainService | 未登录，url:{}", request.getRequestURI());
            throw new ImException(HttpCode.NO_LOGIN);
        }
        request.setAttribute(ImPlatformContants.SESSION, userSession);
        return HttpCode.SUCCESS;
    }

    @Override
    public int getOrder() {
        return Objects.isNull(authRuleOrder) ? RuleEnum.AUTH.getCode() : authRuleOrder;
    }

    @Override
    protected String getServiceName() {
        return RuleEnum.AUTH.getMesaage();
    }
}
